<?php
/***************************************************************************
 * SwordMouse CMS
 * $Id: mysession.php 5 2010-08-02 18:27:51Z dan@inkping.com $
 * Translated and adapted from Marco Baldini's original.
 * - Added phpdoc compatibility.
 * @package ThirdPartyClasses
 */
//  ----------------------------------------------------------------------
//	|	My Session By Marco Baldini (info [at] marcobaldini [dot] com)      |
//  ----------------------------------------------------------------------
// |	My session is a class that stores session data in a database rather |
// |	than files. This method in most secure that the default session     |
// |	system of PHP                                                       |
//  ----------------------------------------------------------------------		
// |	System Requirements: A web server that support PHP (at least 4.2.0  |
// |	for incoming PostreSQL support) and a DBMS up and running. If you   |
// |	chose MySQL you need at least MySQL 4.0.2.                          |
//  ----------------------------------------------------------------------		
// |  Tested on PHP 4.3.8 and MySql 4.1.3b                                |
//  ----------------------------------------------------------------------	
// |  ATTENTION: The support for PostgreSQL will be implemented in the    |
// |  next minor release (1.2.0).                                         |
//  ----------------------------------------------------------------------	
// | This class has been created and released under the GNU GPL and is    |
// | free to use and redistribute only if this whole header comments and  |
// | copyright statement are not removed. Author gives no warranties. Use |
// | at your own risk. Read the copyright, change log, howto and license. |
//  ----------------------------------------------------------------------

/**
 * Invocation:
 *	require_once('config.DB_eSession.php');
 *	require_once('class.DB_eSession.php');
 *	$smSession = new my_session($_MYSESSION_CONF);
 */
class my_session {
	var $session_id;
	var $connessione;
	var $_MYSESSION_CONF;
	var $VARS = array();
	var $forced_expire;
	var $version="1.1";

	/**
	 * @return unknown_type
	 */
	function get_version() {		
		return $this->version;		
	}

	/**
	 * 
	 */
	function get_var($name) {			
		return $this->VARS["$name"];			
	}

	/**
	 * registra variabili
	 */
	function registra($nome,$valore) {			
		if ($this->_MYSESSION_CONF['CRIPT']==1) {
			$cond = "AES_ENCRYPT('".$nome."','".$this->_MYSESSION_CONF['CRIPT_KEY']."')=".$this->_MYSESSION_CONF['NOME'];
		} else {
			$cond = $this->_MYSESSION_CONF['NOME']."='$nome'";
		}	
		$cond .= " AND ".$this->_MYSESSION_CONF['SID']."='".$this->session_id."'";
		$this->delete($this->_MYSESSION_CONF['TB_NAME'],$cond,$this->_MYSESSION_CONF['DB_DATABASE']);	
		$this->insert($this->_MYSESSION_CONF['TB_NAME'],$this->_MYSESSION_CONF['DB_DATABASE'],$nome,$valore);
		$this->get_variabili_di_sessione();
	}

	//deregistra variabili
	function cancella($nome) {
			if ($this->_MYSESSION_CONF['CRIPT']==1) {
			
				$cond = "AES_ENCRYPT('".$nome."','".$this->_MYSESSION_CONF['CRIPT_KEY']."')=".$this->_MYSESSION_CONF['NOME'];
				
			} else {
	
				$cond = $this->_MYSESSION_CONF['NOME']."='$nome'";
				
			}	
			
			$cond .= " AND ".$this->_MYSESSION_CONF['SID']."='".$this->session_id."'";
				
			$this->delete($this->_MYSESSION_CONF['TB_NAME'],$cond,$this->_MYSESSION_CONF['DB_DATABASE']);
			$this->get_variabili_di_sessione();
	}
	
	//costruttore PHP 5
	function __construct($config) {
	
		$this->_MYSESSION_CONF=$config;
			
		$this->db_connection();
		
		$this->sessionid();
		
		//echo "<hr>".$this->session_id."<hr>";
		
		if ($this->controllo_expire_forzato()) $this->destroy();
		
		$_REQUEST[$this->_MYSESSION_CONF['SESSION_VAR_NAME']]=$this->session_id;
	
	}

	//distruttore PHP5
	function __destruct() {
	
		//elimino le variabili di sessione da DB
		$cond=$this->_MYSESSION_CONF['SID']."='".$this->session_id."'";
		$tabelle=$this->_MYSESSION_CONF['TB_NAME'];
	
		$this->delete($this->_MYSESSION_CONF['TB_NAME'],$cond,$this->_MYSESSION_CONF['DB_DATABASE']);	
	
	}
	
	//------FUNZIONI PRIVATE-------//
	function controllo_expire_forzato() {	
		
		if (time()>$this->forced_expire) return 0;
			else return 1;	
	}


	function get_variabili_di_sessione() {
		
		$this->VARS = array();
		
		$cond=$this->_MYSESSION_CONF['SID']."= '".$this->session_id."'";
		$tabelle=$this->_MYSESSION_CONF['TB_NAME'];
		
		//aggiorno la scadenza della sessione
		$campi_upd=$this->_MYSESSION_CONF['EXP']."=".(time()+($this->_MYSESSION_CONF['DURATA']));
	
		$this->update($campi_upd,$tabelle,$cond,$this->_MYSESSION_CONF['DB_DATABASE']);
		
		//prelevo le variabili e le metto bell'array VARS		
			if ($this->_MYSESSION_CONF['CRIPT']==1) {
			
				$campi="AES_DECRYPT(".$this->_MYSESSION_CONF['VALORE'].",'".$this->_MYSESSION_CONF['CRIPT_KEY']."') as valore, AES_DECRYPT(".$this->_MYSESSION_CONF['NOME'].",'".$this->_MYSESSION_CONF['CRIPT_KEY']."') as nome";
				
			} else {
	
				$campi=$this->_MYSESSION_CONF['VALORE']." as valore, ".$this->_MYSESSION_CONF['NOME']." as nome";			
			}		
			
		$r=$this->select($campi,$tabelle,$cond,$this->_MYSESSION_CONF['DB_DATABASE']);
		
		while ($dati=mysql_fetch_array($r)) {
		
	
	
			$this->VARS[$dati["nome"]]=$dati["valore"];
			
		}
	}

	//cerco l'id della sessione, se non lo trovo lo creo nuovo
	function sessionid() {
	
		if ($this->_MYSESSION_CONF['USE_COOKIE']==true) { //cookie abilitati
			
			if (isset($_COOKIE[$this->_MYSESSION_CONF['SESSION_VAR_NAME']])) { // il cookie contiene qualcosa
				
				$this->session_id=$_COOKIE[$this->_MYSESSION_CONF['SESSION_VAR_NAME']];
				
			} else { // cerco l'ID tra i request
				
				if (isset($_REQUEST[$this->_MYSESSION_CONF['SESSION_VAR_NAME']])) {//essite un id in request!
					
					$this->session_id	= $_REQUEST[$this->_MYSESSION_CONF['SESSION_VAR_NAME']];
					$this->get_variabili_di_sessione();
					
				} else { // creo il nuovo ID e lo piazzo nel cookie
					$this->new_sid();
					setcookie ($this->_MYSESSION_CONF['SESSION_VAR_NAME'], $this->session_id,time()+$this->_MYSESSION_CONF['DURATA']);	
				}
				
			}
			
		} else { //cerco altrove
	
				if (isset($_REQUEST[$this->_MYSESSION_CONF['SESSION_VAR_NAME']])) {//esiste l'id!
					
					$this->session_id	= $_REQUEST[$this->_MYSESSION_CONF['SESSION_VAR_NAME']];
					$this->get_variabili_di_sessione();
					
				} else { // creo il nuovo ID
					
					$this->new_sid();			
					
				}
			
		}	
		
	}

	//funzione per creare un nuovo id di sessione univoco
	function new_sid() {
		
		$this->session_id=$this->genera_stringa();
		
		while ( $this->get_num($this->_MYSESSION_CONF['SID'],$this->_MYSESSION_CONF['TB_NAME'],$this->_MYSESSION_CONF['DB_DATABASE'],$this->session_id) > 0 ) {
		
			$this->session_id=$this->genera_stringa();
			
		}
	
		$this->forced_expire = time()+ $this->_MYSESSION_CONF['MAX_DURATA'];
		
	}
	
	//generero una stringa casuale
	function genera_stringa()
	{
		
	 	$alfabeto="qazxswedcvfrtgbnhyujmklpoi0987654321";
	 	$ris='';
		
		for ($i=0; $i < $this->_MYSESSION_CONF['SID_LEN']; $i++) {
			srand($this->make_seed());		
			$ris .= $alfabeto[rand(0,(strlen($alfabeto)-1))];
		}
		
		return($ris);
	}
	
	//funzione casuale per l'inizializzazione del generatore di numeri casuali
	function make_seed()
	{
	   list($usec, $sec) = explode(' ', microtime());
	   return (float) $sec + ((float) $usec * 100000);
	}
	
	//connessione al database mysql
	function db_connection() {
	
	if (!is_resource($this->connessione))
		$this->connessione = mysql_pconnect($this->_MYSESSION_CONF['DB_SERVER'],$this->_MYSESSION_CONF['DB_USERNAME'],$this->_MYSESSION_CONF['DB_PASSWORD']) or die("Connessione non riuscita: " . mysql_error());
		
	}
	
	//--------------------FUNZIONI MYSQL
	
	//Numero dei risultati 
	function get_num($campo,$tab,$db,$valore) {
		
		$query="select count(*) from $db.$tab where $campo = '$valore'";	
		//echo "<hr>$query<hr>";
		$val=mysql_result(mysql_query($query,$this->connessione),0,0);	
		return $val;
		
	}
	
	//select
	function select($campi,$tabelle,$cond,$db) {
	
		$query="SELECT $campi FROM $db.$tabelle WHERE $cond";
		//echo "<hr>$query<hr>";
		$val=mysql_query($query,$this->connessione) or die("Sel:".mysql_error());
		
		return $val;
	
	}
	
	//update
	function update($campi,$tabelle,$cond,$db) {
		
		$query="UPDATE $db.$tabelle SET $campi WHERE $cond";
		//echo "<hr>$query<hr>";
		$val=mysql_query($query,$this->connessione) or die("Upd:".mysql_error());
		
		return $val;
	
	}

	//delete
	function delete($tabelle,$cond,$db) {
		
		$query="DELETE FROM $db.$tabelle WHERE $cond";
		//echo "<hr>$query<hr>";
		$val=mysql_query($query,$this->connessione) or die("Del:".mysql_error());
		
		return $val;
	
	}

	//insert
	function insert($tabelle,$db,$nome,$val) {
		
		if ($this->_MYSESSION_CONF['CRIPT']==1) {
			$nome= "AES_ENCRYPT('".$nome."','".$this->_MYSESSION_CONF['CRIPT_KEY']."')";
			$val= "AES_ENCRYPT('".$val."','".$this->_MYSESSION_CONF['CRIPT_KEY']."')";
		} else {
			$nome= "'".$nome."'";
			$val= "'".$val."'";
		}
		
		$query="INSERT INTO $db.$tabelle (sid,expires,nome,valore) VALUES ('".$this->session_id."','".(time()+$this->_MYSESSION_CONF['DURATA'])."',$nome,$val)";
		//echo "<hr>$query<hr>";
		$val=mysql_query($query,$this->connessione) or die("Ins:".mysql_error());
		
		return $val;
	
	}
}
?>